package com.bmth.alise.utils;

import java.util.HashMap;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.bmth.alise.conf.Configuration;

public class MQReceiver {

	private static MQReceiver instance = new MQReceiver();
	private Map<String, MessageConsumer> mcmap = new HashMap<>();
	private Map<String, MessageProducer> mpmap = new HashMap<>();
	private Map<String, TextMessage> txmap = new HashMap<>();

	public static MQReceiver getInstance() {
		return instance;
	}

	private MQReceiver() {
		try {
			String MQUrl = Configuration.getProperty("MQUrl");
			Connection connection = new ActiveMQConnectionFactory(MQUrl).createConnection();
			connection.start();

			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			for (String queueStr : QueueUtils.queues) {
				Queue queue = session.createQueue(queueStr);
				mcmap.put(queueStr, session.createConsumer(queue));
				mpmap.put(queueStr, session.createProducer(queue));
				txmap.put(queueStr, session.createTextMessage());
			}

		} catch (JMSException e) {
			e.printStackTrace();
		}

	}

	public String receive(String queue) {
		try {
			Message message = mcmap.get(queue).receive(1000);
			TextMessage txtMsg = (TextMessage) message;
			return txtMsg == null ? "" : txtMsg.getText();
		} catch (JMSException e) {
			e.printStackTrace();
		}
		return null;
	}
}